<template>
	<view class="h-fill">
		<u-navbar title="会员中心" :background="navBg" :borderBottom="false" titleColor="#fff" :isBack="false"></u-navbar>
		<image class="h-fill u-p-bg" mode="widthFix"
			src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/bg.png"></image>
		<view style="position: relative;z-index: 98;">
			<view class="pad-l-base pad-r-base pad-t-base">
				<view v-if="hasLogin">
					<view v-if="vipCards.length" class="pos-real">
						<u-swiper :current="cardIdx" :list="vipCards" @change="cardChange" name="cardImageUrl"
							:height="372" :autoplay="false" mode="none" :border-radius="24"></u-swiper>
						<view class="pos-abs-fill">
							<view class="fill pad-l-sm pad-t-sm pad-b-sm text-white flex-v">
								<view class="h-box">
									<image @click="handleEdit"
										:src="userInfo.avatar || 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/user.png'"
										class="user-head"></image>
									<view class="mg-l-xs flex-extend u-line-1" style="word-break: break-all;">
										<view class="h-box">
											<view v-if="userInfo.nickname" class="flex-extend u-line-1 uni-bold"
												style="font-size: 34rpx;line-height: 1.3;">{{userInfo.nickname}}</view>
											<view v-else class="h-box flex-extend">
												<view style="font-size: 34rpx;">未设置</view>
												<view>
													<get-wx-userinfo @change='handleBind'>
														<text
															class="uni-text-gray uni-text-underline text-sm">去设置</text>
													</get-wx-userinfo>
												</view>
											</view>
											<view @click="navToVipRights" class="pos-real mg-l-xs"
												style="align-self: flex-start;">
												<image
													src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/img_wode_huiyuan@2x.png"
													style="width: 206rpx;height: 68rpx;vertical-align: bottom;"></image>
												<view class="pos-abs-fill h-box justify-center">
													<image style="width: 38rpx;height: 32rpx;margin-right: 12rpx;"
														src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_huiyuan.png">
													</image>
													<text>会员权益</text>
												</view>
											</view>
										</view>
										<view class="h-box">
											<image v-if="userInfo.gender === 1" class="img-gender"
												src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_nan@2x.png">
											</image>
											<image v-else class="img-gender"
												src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_nv@2x.png">
											</image>
											<text>{{userInfo.mobile || ''}}(ID:{{userInfo.id || '-'}})</text>
										</view>
									</view>
								</view>
								<view class="flex-extend"></view>
								<view class="h-box pad-r-sm">
									<view class="flex-extend">
										<text
											class="mg-r-sm">有效期截止：{{$formatTime(vipCards[cardIdx].expirationTime).substring(0, 10)}}</text>
										<u-button @click="handleRenewal" shape="circle" size="mini"
											:custom-style="{'background-color': '#F4DB21', 'color': '#F4DB21', 'width': '120rpx', 'height': '50rpx'}">
											<text class="text-dark">续期</text>
										</u-button>
									</view>
									<image @click="showQRCodeView" class="img-code"
										src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_erweima@2x.png">
									</image>
								</view>
							</view>
						</view>
					</view>
					<view v-else class="pos-real" style="height: 372rpx;">
						<image
							src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/img_wode_putong.png"
							class="h-fill" mode="widthFix"></image>
						<view class="pos-abs-fill">
							<view class="fill pad-l-sm pad-t-sm pad-b-sm text-white flex-v">
								<view class="h-box">
									<image @click="handleEdit"
										:src="userInfo.avatar || 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/user.png'"
										class="user-head" style="align-self: flex-start;"></image>
									<view class="mg-l-xs flex-extend u-line-1" style="word-break: break-all;">
										<view class="h-box">
											<view v-if="userInfo.nickname" class="flex-extend u-line-1 uni-bold"
												style="font-size: 34rpx;line-height: 1.3;">{{userInfo.nickname}}</view>
											<view v-else class="h-box flex-extend">
												<view style="font-size: 34rpx;">未设置</view>
												<view>
													<get-wx-userinfo @change='handleBind'>
														<text
															class="uni-text-gray uni-text-underline text-sm">去设置</text>
													</get-wx-userinfo>
												</view>
											</view>
											<view @click="navToVipRights" class="pos-real mg-l-xs"
												style="align-self: flex-start;">
												<image
													src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/img_wode_huiyuan@2x.png"
													style="width: 206rpx;height: 68rpx;vertical-align: bottom;"></image>
												<view class="pos-abs-fill h-box justify-center">
													<image style="width: 38rpx;height: 32rpx;margin-right: 12rpx;"
														src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_huiyuan.png">
													</image>
													<text>会员权益</text>
												</view>
											</view>
										</view>
										<view class="h-box">
											<image v-if="userInfo.gender === 1" class="img-gender"
												src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_nan@2x.png">
											</image>
											<image v-else class="img-gender"
												src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_nv@2x.png">
											</image>
											<text>{{userInfo.mobile || '-'}}(ID:{{userInfo.id || '-'}})</text>
										</view>
									</view>
								</view>
								<view class="flex-extend flex-h justify-end pad-r-base" style="align-items: flex-end;">
									<image @click="showQRCodeView" class="img-code"
										src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_erweima@2x.png">
									</image>
								</view>
							</view>
						</view>
					</view>
					<view @click="cardIdx = cardIdx === 0 ? 1 : 0" class="h-box justify-center pad-b-sm">
						<view v-if="vipCards.length > 1" class="pos-real vip-indicator">
							<view class="pos-abs-lt pos-abs-lb vip-indicator-thumb"
								:class="{'vip-indicator-thumb-right': cardIdx === 1}"></view>
						</view>
					</view>
				</view>
				<view v-else class="pos-real mg-b-sm" style="height: 372rpx;">
					<image
						src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/img_wode_putong.png"
						class="h-fill" mode="widthFix"></image>
					<view class="pos-abs-fill">
						<view class="fill pad-l-sm pad-t-sm pad-b-sm text-white flex-v">
							<view class="h-box">
								<navigator url="/pagesFoo/public/login" class="flex-extend">
									<view class="h-box">
										<image
											src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/user.png"
											class="user-head"></image>
										<view class="mg-l-xs pad-r-xs" style="word-break: break-all;">
											去登录
										</view>
									</view>
								</navigator>
								<view @click.stop="navToVipRights" class="pos-real">
									<image
										src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/img_wode_huiyuan@2x.png"
										style="width: 206rpx;height: 68rpx;vertical-align: bottom;"></image>
									<view class="pos-abs-fill h-box justify-center">
										<image style="width: 38rpx;height: 32rpx;margin-right: 12rpx;"
											src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_wode_huiyuan.png">
										</image>
										<text>会员权益</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="pos-real bg-white menu-wrapper">
				<view class="wallet pos-real mg-b-base" style="height: 151rpx">
					<image class="round-corner h-fill" style="vertical-align: bottom;" mode="widthFix"
						:src="$getCloudStorageUrl('/img_wode_qianbao@2x.png')"></image>
					<view class="pos-abs-fill h-box">
						<view class="flex-extend">
							<uni-grid @change="handleGridChange" :column="3" :square="false" :showBorder="false"
								class="h-fill">
								<uni-grid-item :index="0">
									<view class="v-box fill text-white">
										<text
											class="uni-bold uni-text-big">{{(((userInfo.teamTotalIncome + userInfo.personalTotalIncome) || 0) / 100).toFixed(2)}}</text>
										<text>总收益</text>
									</view>
								</uni-grid-item>
								<uni-grid-item :index="1">
									<view class="v-box fill text-white">
										<text
											class="uni-bold uni-text-big">{{((userInfo.account.balance || 0) / 100).toFixed(2)}}</text>
										<text>可用资产</text>
									</view>
								</uni-grid-item>
								<uni-grid-item :index="2">
									<view class="v-box fill text-white">
										<text class="uni-bold uni-text-big">{{userInfo.teamCount || '0'}}</text>
										<text>团队人数</text>
									</view>
								</uni-grid-item>
							</uni-grid>
						</view>
					</view>
				</view>
				<view class="h-box">
					<view class="h-box block-gray flex-extend" @click="clickMyMotorcade">
						<view class="flex-extend">
							<view class="text-title">我的车队</view>
							<view class="uni-text-gray">预约车队{{ motorcadeTotal }}条</view>
						</view>
						<image
							src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_img_chedui@2x.png">
						</image>
					</view>
					<view class="pad-l-sm"></view>
					<view class="h-box block-gray flex-extend" @click="clickMyCollect">
						<view class="flex-extend">
							<view class="text-title">我的收藏</view>
							<view class="uni-text-gray">共{{ collectTotal }}条</view>
						</view>
						<image
							src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_img_shouc@2x.png">
						</image>
					</view>
				</view>
				<view>
					<view class="h-box">
						<view class="flex-extend h-box pad-t-sm pad-b-sm">
							<image style="width: 36rpx;height: 36rpx;" class="mg-r-xs"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_gongneng@2x.png">
							</image>
							<text class="text-title">其他功能</text>
						</view>
						<view class="uni-text-gray" @click="cltest">快来看看吧~</view>
					</view>
					<view class="h-box flex-wrap">
						<view @click="navToPage('../../pagesFoo/order/order')" class="v-box mg-b-base"
							style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_dingdan@2x.png">
							</image>
							<view class="mg-t-xs">我的订单</view>
						</view>
						<view @click="navToVipCard" class="v-box mg-b-base" style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_huiyuanka@2x.png">
							</image>
							<view class="mg-t-xs">会员卡</view>
						</view>
						<view @click="handleRent" class="v-box mg-b-base" style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_qianbao@2x.png">
							</image>
							<view class="mg-t-xs">物品租借</view>
						</view>
						<view @click="navToPage('../../pagesUser/platform/share-expert-home')" class="v-box mg-b-base"
							style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_daren@2x.png">
							</image>
							<view class="mg-t-xs">达人后台</view>
						</view>
						<view @click="navToPage('/pagesGroup/platform/ticket-list')" class="v-box mg-b-base"
							style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_taopiao@2x.png">
							</image>
							<view class="mg-t-xs">兑换套票</view>
						</view>
						<view @click="handleExchange" class="v-box mg-b-base" style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_shangpin@2x.png">
							</image>
							<view class="mg-t-xs">商品兑换</view>
						</view>
						<!-- <view class="v-box mg-b-base" style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;" src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_juese@2x.png"></image>
							<view class="mg-t-xs">角色信息</view>
						</view> -->
						<view @click="navToServicePage" class="v-box mg-b-base" style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_kefu@2x.png">
							</image>
							<view class="mg-t-xs">联系客服</view>
						</view>
						<view @click="navToPage('/pagesMarketing/task-list')" class="v-box mg-b-base"
							style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_sign@2x.png">
							</image>
							<view class="mg-t-xs">签到积分</view>
						</view>
						<!-- <view @click="navToPage('/pagesAuth/auth')" class="v-box mg-b-base" style="width: 25%;">
							<image style="width: 52rpx;height: 52rpx;"
								src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_sign@2x.png">
							</image>
							<view class="mg-t-xs">实名认证</view>
						</view> -->
					</view>
				</view>
			</view>
		</view>
		<view class="qrcode-wrapper" v-if="qrcodeVisible" @click.stop="hideQRCodeView">
			<view class="lb-p" :style="{width: popupWidth + 'px', height: popupHeight + 'px'}">
				<image class="lb-p-bg h-fill" mode="widthFix"
					src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/img_tanchuang_bg_1@2x.png">
				</image>
				<view class="lb-p-c uni-flex uni-column align-center">
					<text class="uni-bold uni-text-normal">会员核销码</text>
					<view class="uni-flex-extend uni-flex align-center" style="height: calc(100% - 40rpx);">
						<canvas class="qrcode-wrapper-content-qrcode" canvas-id="qrcode" />
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popupExchange">
			<view class="popup-exchange">
				<image class="h-fill v-fill" mode="aspectFill" :src="$getCloudStorageUrl('/img_tanchuang_bg@2x.png')">
				</image>
				<view class="popup-exchange-content uni-flex uni-column">
					<view class="uni-center uni-bold">
						<text>商品兑换</text>
					</view>
					<view>
						<input v-model="exchangeCode" placeholder="请输入兑换码" />
					</view>
					<view class="uni-flex align-center">
						<u-button class="uni-flex-extend" shape="circle" @click="cancelExchange">取消</u-button>
						<view class="l-pad"></view>
						<u-button class="uni-flex-extend" type="error" shape="circle"
							@click="confirmExchange">兑换</u-button>
					</view>
				</view>
			</view>
		</uni-popup>
		<u-popup v-model="popupPledgeVisible" mode="center">
			<view class="pos-real">
				<image :src="$getCloudStorageUrl('/tanchuang.png')"
					style="width: 620rpx;height: 367rpx;vertical-align: bottom;"></image>
				<view class="pos-abs-fill">
					<view class="text-white" style="padding: 105rpx 48rpx 0 48rpx;">
						进出门店需扫码哟，会员进店超过15小时未扫离店码，将扣除押金20元，进店时扣取，离店时退还。</view>
					<view class="h-box justify-around pos-abs-lb pos-abs-rb uni-center" style="height: 98rpx;">
						<view @click="popupPledgeVisible = false" class="uni-text-gray flex-extend"
							style="font-size: 34rpx;">知道了</view>
						<view @click="handleRecharge" class="flex-extend" style="color: #5D5AE2;font-size: 34rpx;">
							缴纳扫码押金</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- <u-popup v-model="popupNicknameVisible" mode="bottom">
			<view>
				<nice-red-button text="设置昵称"></nice-red-button>
			</view>
		</u-popup> -->
		<u-modal ref="modalProfile" v-model="modalAvatarVisible" asyncClose title="完善信息" confirmText="保存"
			@confirm="confirmProfile">
			<!-- <get-wx-userinfo @change='handleBind'>
				<view class="btn-set-nickname">使用微信头像和昵称</view>
			</get-wx-userinfo> -->
			<view class="pad-l-base pad-r-base">
				<u-form :model="profileForm" ref="profileForm">
					<u-form-item label="头像" prop="avatar">
						<view>
							<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
								<u-image class="avatar"
									:src="profileForm.avatar || 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/default-avatar.png'"
									width="100%" height="100%"></u-image>
							</button>
						</view>
					</u-form-item>
					<u-form-item label="昵称" prop="nickname">
						<u-input v-model="profileForm.nickname" placeholder="请输入昵称" type="nickname" />
					</u-form-item>
				</u-form>
			</view>
		</u-modal>
	</view>
</template>
<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js'
	import {
		getUserInfo,
		refreshQrcode,
		exchangeGoods,
		updateUserInfo,
		getMyMotorcade
	} from "../../api/platform/user.js"
	import {
		genRechargeOrder,
		genOpenVipOrder,
		genPayInfo,
		getOrderDetail
	} from "../../api/platform/order.js"
	const walletBgRatio = 4.4;
	const popupBgRatio = 1;

	const db = uniCloud.database()
	const dbCmd = db.command
	const $ = dbCmd.aggregate

	const storeSigner = uniCloud.importObject('storeSigner', {
		customUI: true
	})
	const userProfile = uniCloud.importObject('userInfo', {
		customUI: true
	})
	const authUtil = uniCloud.importObject('authUtil')
	export default {
		data() {
			return {
				navBg: {
					'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)'
				},
				popupWidth: 200,
				popupHeight: 200,
				codeReady: false,
				qrcodeVisible: false,
				secrecyOn: true,
				exchangeCode: '',

				cardIdx: 0,
				popupPledgeVisible: false,
				popupNicknameVisible: true,

				motorcadeTotal: 0,
				collectTotal: 0,

				modalAvatarVisible: false,
				profileForm: {
					avatar: '',
					nickname: ''
				},
				profileFormRules: {
					nickname: [{
						required: true,
						message: '请输入昵称',
						trigger: ['change', 'blur']
					}],
					avatar: [{
						required: true,
						message: '请选择头像',
						trigger: ['change', 'blur']
					}]
				}
			}
		},
		computed: {
			...mapState(['hasLogin', 'userInfo', 'wxLoginCode']),
			vipCards() {
				let t = []
				if (this.hasLogin && this.userInfo.vipInfo) {
					if (this.userInfo.vipInfo.storeVipCardInfo) {
						t.push(this.userInfo.vipInfo.storeVipCardInfo)
					}
					if (this.userInfo.vipInfo.merchantVipCardInfo) {
						t.push(this.userInfo.vipInfo.merchantVipCardInfo)
					}
				}
				return t
			}
		},
		watch: {
			hasLogin(newVal) {
				if (newVal) {
					this.loadData()
					if (this.storeSign) {
						console.log("0", this.storeSign, this.codeId, this.rewards)
						this.handleStoreSign(this.codeId, this.rewards)
					}
				}
			},
			popupPledgeVisible(newVal) {
				if (newVal) {
					uni.hideTabBar()
				} else {
					uni.showTabBar()
				}
			},
			qrcodeVisible(newVal) {
				if (newVal) {
					if (newVal) {
						uni.hideTabBar()
					} else {
						uni.showTabBar()
					}
				}
			}
		},
		onLoad(e) {
			if (e.q) {
				console.log("q", e)
				let paramArr = decodeURIComponent(e.q).split('store-sign?')[1].split('&')
				let storeSign, codeId, rewards
				for (let item of paramArr) {
					let cache = item.split('=')
					console.log("1", cache)
					switch (cache[0]) {
						case 'storeSign':
							storeSign = cache[1]
							break
						case 'codeId':
							codeId = cache[1]
							break
						case 'rewards':
							rewards = cache[1]
							break
					}
				}
				if (storeSign && codeId && rewards != undefined) {
					console.log("2", storeSign, codeId, rewards)
					this.handleStoreSign(codeId, rewards)
				}
			} else {
				console.log("3", e)
				if (e.storeSign && e.codeId && e.rewards != undefined) {
					this.handleStoreSign(e.codeId, e.rewards)
				}
			}
		},
		created() {
			let sysInfo = uni.getSystemInfoSync()
			this.popupWidth = sysInfo.windowWidth - uni.upx2px(20) * 2;
			this.popupHeight = this.popupWidth / popupBgRatio;

			let t = uni.getStorageSync("secrecyOn");
			if (t === undefined) {
				this.secrecyOn = true
			}
		},
		onShow() {

			if (this.hasLogin && (!this.userInfo.avatar || !this.userInfo.nickname)) {
				this.modalAvatarVisible = true
				this.$nextTick(() => {
					this.$refs.profileForm.setRules(this.profileFormRules);
				})
			}
		},
		onReady() {
			this.loadData();
		},
		async onTabItemTap(e) {
			if (e.index !== 2) return
			uni.showLoading({
				mask: true
			})
			await this.loadData()
			uni.hideLoading()
		},
		async onPullDownRefresh() {
			await this.loadData()
			uni.stopPullDownRefresh()
		},
		methods: {
			...mapMutations(['updateUserInfo', 'setWxLoginCode']),
			// async navToAuth() {
			// 	let p = await authUtil.genAuthReqParams()
			// 	wx.navigateToMiniProgram({
			// 		appId: 'wx88736d7d39e2eda6',
			// 		path: 'pages/oauth/authindex',
			// 		extraData: p
			// 	})
			// },
			confirmProfile() {
				this.$refs.profileForm.validate(async valid => {
					if (valid) {
						uni.showLoading({
							mask: true
						})
						try {
							if (!this.fileID) {
								let i = this.profileForm.avatar.lastIndexOf('.')
								let suffix = ''
								if (i != -1) {
									suffix = this.profileForm.avatar.substring(i)
								}
								let res = await uniCloud.uploadFile({
									cloudPath: `avatars/${this.userInfo.id}${Date.now()}${suffix}`,
									filePath: this.profileForm.avatar
								})
								this.fileID = res.fileID
							}
							if (!this.profileForm.avatar.startsWith('http')) {
								let res = await uniCloud.getTempFileURL({
									fileList: [this.fileID]
								})
								let tempFile = res.fileList[0]
								console.log('tempFile', tempFile)
								if (tempFile.download_url) {
									this.profileForm.avatar = tempFile.download_url
								}
							}
							await userProfile.completeProfile({
								avatar: this.profileForm.avatar,
								nickname: this.profileForm.nickname
							})
							let userInfo = Object.assign(this.userInfo, {
								avatar: this.profileForm.avatar,
								nickname: this.profileForm.nickname
							})
							uni.hideLoading()
							this.updateUserInfo(userInfo)
							this.modalAvatarVisible = false
						} catch (e) {
							console.error(e)
							this.$refs.modalProfile.clearLoading()
							this.$showError(e.message)
						}
					} else {
						this.$refs.modalProfile.clearLoading()
					}
				});
			},
			onChooseAvatar(e) {
				console.log('onChooseAvatar', e)
				this.profileForm.avatar = e.detail.avatarUrl
			},
			async handleStoreSign(codeId, rewards) {
				try {
					uni.showLoading({
						mask: true
					})
					console.log("rewards:", rewards)
					await storeSigner.userSign(codeId, rewards)
					uni.hideLoading()
					delete this.storeSign
					delete this.codeId
					delete this.rewards
					this.$toast('签到成功！').then(() => {
						uni.navigateTo({
							url: '/pagesMarketing/task-list'
						})
					})
				} catch (e) {
					uni.hideLoading()
					if (/未登录/.test(e)) {
						this.storeSign = true
						this.codeId = codeId
						this.rewards = rewards
						uni.navigateTo({
							url: '/pagesFoo/public/login'
						})
					} else {
						delete this.storeSign
						delete this.codeId
						delete this.rewards
						this.$showError(e.errMsg || e.message || e)
					}
				}
			},
			handleEdit() {
				uni.navigateTo({
					url: './edit?id=' + this.userInfo.id
				})
			},
			clickMyCollect() {
				uni.navigateTo({
					url: '/pagesUser/my-collect'
				})
			},
			clickMyMotorcade() {
				uni.navigateTo({
					url: '/pagesUser/my-motorcade'
				})
			},
			async handleBind(data) {
				this.modalAvatarVisible = false
				try {
					data.code = this.wxLoginCode
					let userInfo = await updateUserInfo(data)
					this.updateUserInfo(userInfo);
					this.$toast("设置成功")
				} catch (e) {
					this.$log("更新用户信息失败", e);
					if (e.code == 500) {
						uni.login({
							success: (codeRes) => {
								data.code = codeRes.code
								this.setWxLoginCode(codeRes.code)
								this.handleBind(data)
							},
							fail: (err) => {
								this.$showError(err)
							}
						})
					}
				}
			},
			navToVipCard() {
				uni.navigateTo({
					url: '/pagesUser/vip-cards'
				})
			},
			handleRent() {
				if (!this.hasLogin) {
					this.showLoginModal();
					return
				}
				// #ifndef H5
				uni.scanCode({
					scanType: ["qrCode"],
					success: (res) => {
						let matches = /rent-goods\?shopId=\w{1,}@/.exec(res.result);
						if (matches && matches.length) {
							let t = matches[0]
							let shopId = t.replace('rent-goods?shopId=', '').replace('@', '')
							uni.navigateTo({
								url: '/pagesUser/rent-goods?shopId=' + shopId
							})
						} else {
							uni.showModal({
								content: '未获取到门店信息',
								cancelText: '联系客服',
								confirmText: '重试',
								success: (res) => {
									if (res.confirm) {
										this.handleRent()
									} else {
										this.$copy("i3d008", () => {
											uni.showModal({
												content: '客服微信已复制，请添加客服好友',
												showCancel: false,
												confirmText: '朕知道了'
											})
										})
									}
								}
							})
						}
					}
				})
				// #endif
			},
			async handleRenewal() {
				uni.showLoading({
					mask: true
				})
				try {
					let vipCard = this.vipCards[this.cardIdx];
					let order = await genOpenVipOrder({
						vipCardId: vipCard.cardId,
						showLoading: false
					})
					let orderPayInfo = await genPayInfo({
						orderId: order._id,
						showLoading: false
					});
					uni.showLoading({
						mask: true,
						title: '检测支付环境'
					})
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: orderPayInfo.timeStamp,
						nonceStr: orderPayInfo.nonceStr,
						package: orderPayInfo.package,
						signType: orderPayInfo.signType,
						paySign: orderPayInfo.paySign,
						success: async (res) => {
							console.log('支付成功', res)
							uni.hideLoading()
							let success = await this.finishPay(order)
							if (success) {
								this.$toast("续费成功")
							}
						},
						fail: (err) => {
							console.log('用户取消支付', err)
							uni.hideLoading()
						}
					})
				} catch (e) {
					console.error(e)
					uni.hideLoading()
				}
			},
			async finishPay(order) {
				try {
					order = await getOrderDetail({
						id: order._id
					})
					if (order.status === 5) {
						let currentRegion = uni.getStorageSync('currentRegion')
						let currentCityCode = currentRegion.city.value
						let userInfo = await getUserInfo({}, currentCityCode)
						this.updateUserInfo(userInfo)
						return true
					}
				} catch (e) {
					console.error(e)
					uni.showModal({
						content: '查询支付状态遇到错误！',
						cancelText: '联系客服',
						confirmText: '重试',
						success: (res) => {
							if (res.confirm) {
								this.finishPay(order)
							} else {
								this.$copy("i3d008", () => {
									uni.showModal({
										content: '客服微信已复制，请添加客服好友',
										showCancel: false,
										confirmText: '朕知道了'
									})
								})
							}
						}
					})
				}
			},
			async handleRecharge() {
				uni.showLoading({
					mask: true
				})
				try {
					let vipCard = this.vipCards[this.cardIdx];
					let order = await genRechargeOrder({
						amount: this.enterPledgeConfig.value,
						showLoading: false
					})
					let orderPayInfo = await genPayInfo({
						orderId: order._id,
						showLoading: false
					});
					uni.showLoading({
						mask: true,
						title: '检测支付环境'
					})
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: orderPayInfo.timeStamp,
						nonceStr: orderPayInfo.nonceStr,
						package: orderPayInfo.package,
						signType: orderPayInfo.signType,
						paySign: orderPayInfo.paySign,
						success: async (res) => {
							console.log('支付成功', res)
							uni.hideLoading()
							let success = await this.finishPay(order)
							if (success) {
								this.$toast("押金支付成功")
								this.popupPledgeVisible = false
								this.showQrcodePopup()
							}
						},
						fail: (err) => {
							console.log('用户取消支付', err)
							uni.hideLoading()
						}
					})
				} catch (e) {
					console.error(e)
					uni.hideLoading()
				}
			},
			cardChange(idx) {
				this.cardIdx = idx
			},
			handleGridChange(e) {
				switch (e.detail.index) {
					case 0:
						this.navToPage("/pagesUser/platform/orders");
						break;
					case 1:
						this.navToPage("/pagesUser/platform/my-account");
						break;
					case 2:
						this.navToPage("/pagesUser/platform/my-team");
						break;
				}
			},
			handleExchange() {
				if (!this.hasLogin) {
					this.showLoginModal();
				} else {
					this.exchangeCode = ''
					this.$refs.popupExchange.open();
				}
			},
			cancelExchange() {
				this.$refs.popupExchange.close();
			},
			cltest() {
				uni.navigateTo({
					url: '/pagesUser/platform/package/static-Package'
				})
			},
			async confirmExchange() {
				if (this.busy) {
					return;
				}
				if (!this.exchangeCode) {
					uni.showToast({
						title: "请输入兑换码",
						icon: "none"
					})
					return;
				}
				this.busy = true;
				uni.showLoading({
					mask: true
				})
				try {
					let userId = uni.getStorageSync('userInfo').id
					let res = await exchangeGoods({
						userId,
						codeId: this.exchangeCode,
						showLoading: false
					});
					this.$refs.popupExchange.close();
					if (res.vipCard) {
						let currentRegion = uni.getStorageSync('currentRegion')
						let currentCityCode = currentRegion.city.value
						let userInfo = await getUserInfo({
							showLoading: false
						}, currentCityCode)
						this.updateUserInfo(userInfo)
						uni.showModal({
							title: "兑换成功",
							content: `恭喜您，您现在是${res.vipCard.name}会员了`,
							showCancel: false,
							confirmText: "朕知道了"
						})
					} else if (res.order) {
						uni.showModal({
							title: "兑换成功",
							content: `兑换的票券可以在会员中心-我的订单中查看`,
							confirmText: "查看票券",
							cancelText: "待会查看",
							success: (res1) => {
								if (res1.confirm) {
									uni.navigateTo({
										url: "/pagesGroup/platform/order-detail?orderId=" +
											res.order._id
									})
								}
							}
						})
					}
					this.busy = false;
					uni.hideLoading()
				} catch (e) {
					this.$log("兑换商品遇到错误", e);
					this.busy = false;
				}
			},
			switchSecrecy() {
				if (!this.hasLogin && this.secrecyOn) {
					this.showLoginModal();
					return;
				}
				this.secrecyOn = !this.secrecyOn;
				uni.setStorage({
					key: "secrecyOn",
					data: this.secrecyOn
				})
			},
			showLoginModal() {
				uni.showModal({
					title: "您还未登陆，请先登录！",
					cancelText: "再看看",
					confirmText: "去登陆",
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: "/pagesFoo/public/login"
							})
						}
					}
				})
			},
			navToPage(url) {
				if (!this.hasLogin) {
					this.showLoginModal();
				} else {
					uni.navigateTo({
						url: url
					})
				}
			},
			navToServicePage() {
				uni.navigateTo({
					url: "/pagesUser/customer-service"
				})
			},
			navToVipRights() {
				if (!this.hasLogin || !this.vipCards.length) {
					uni.navigateTo({
						url: '/pagesUser/vip-cards'
					})
				} else {
					uni.navigateTo({
						url: '/pagesUser/vip-rights'
					})
				}
			},

			async showQRCodeView() {
				// if (this.vipCards.length && this.vipCards[this.cardIdx].settlementWay === 'time' &&
				// 	this.userInfo.account.balance < this.enterPledgeConfig.value) {
				// 	this.popupPledgeVisible = true
				// 	uni.hideTabBar()
				// 	return
				// }
				// try {
				// 	await refreshQrcode({})
				// 	this.qrcodeVisible = true;
				// 	uni.hideTabBar();
				// 	this.make();
				// } catch (e) {
				// 	console.error(e)
				// }
				this.qrcodeVisible = true;
				uni.hideTabBar();
				this.make();
			},
			hideQRCodeView() {
				this.qrcodeVisible = false;
				uni.showTabBar();
			},
			async loadData() {
				if (!this.hasLogin) {
					return;
				}
				uni.showLoading({
					mask: true
				})
				try {
					this.enterPledgeConfig = await this.$dbHelper.getOne("t3ds-system-config", {
						showLoading: false,
						where: `key == 'enterPledge'`
					})
					let currentRegion = uni.getStorageSync('currentRegion')
					let currentCityCode = currentRegion.city.value
					let userInfo = await getUserInfo({
						showLoading: false
					}, currentCityCode);
					this.updateUserInfo(userInfo)

					// 获取车队总条数
					// let orderRes = await db.collection("t3ds-order").aggregate()
					// .match({
					//   user_id: this.userInfo._id,
					//   type: "subscribe",
					//   status: dbCmd.and(dbCmd.gte(1), dbCmd.lte(5)),
					//   ['items.' + 0 + '.start_time']: dbCmd.gt(Date.now())
					// })
					// .addFields({
					//   motorcadeId: '$motorcadeId'
					// })
					// .project({
					//   motorcadeId: 1
					// })
					// .end()
					// let motorcadesArr = orderRes.result.data.map(item => item.motorcadeId)
					// this.motorcadeTotal = [...new Set(motorcadesArr)].length
					let {
						total
					} = await getMyMotorcade({
						showLoading: false,
						pageNum: 1,
						pageSize: 1000,
						userLocation: uni.getStorageSync('userLocation')
					})
					this.motorcadeTotal = total

					// 获取收藏总条数
					let collectRes = await this.$dbHelper.getList("t3ds-collect", {
						showLoading: false,
						where: {
							userId: userInfo.id
						}
					})
					let overdueCount = collectRes.filter(item => item.motorcadeStartTime && item.motorcadeStartTime <=
						Date.now())
					this.collectTotal = collectRes.length - overdueCount.length
				} catch (e) {
					this.$log('error', e);
				} finally {
					uni.hideLoading()
				}
			},
			handleQCodeError(e) {
				this.$log("load qcode error", e);
			},
			make() {
				this.$log('生成会员码');
				let text = ''
				if (this.vipCards.length) {
					text =
						`https://test.the3dspace.cn/vip-charge-off?memberId=${this.userInfo._id}@&cardId=${this.vipCards[this.cardIdx].cardId}@`
				} else {
					text = `https://test.the3dspace.cn/vip-charge-off?memberId=${this.userInfo._id}@`
				}
				uQRCode.make({
					canvasId: 'qrcode',
					componentInstance: this,
					text,
					size: 200,
					margin: 10,
					backgroundColor: '#ffffff',
					foregroundColor: '#000000',
					fileType: 'jpg',
					correctLevel: uQRCode.defaults.correctLevel,
					success: res => {
						// this.$log(res);
						this.codeReady = true;
					},
					fail: err => {
						this.$log('会员码生成出错', err);
					}
				})
			}
		}
	};
</script>
<style lang="scss" scoped>
	.block-gray {
		background: #EFF1F7;
		border-radius: 24px;
		padding: 20rpx 30rpx;
	}

	.block-gray image {
		width: 72rpx;
		height: 72rpx;
	}

	.menu-wrapper {
		padding: 30rpx;
		border-radius: 70rpx 70rpx 0 0;
		background-image: linear-gradient(#ffffff, #F5F5F5);
	}

	/deep/ .u-mode-center-box {
		background-color: transparent !important;
	}

	/deep/ .uni-button,
	button {
		height: auto !important;
	}

	.img-gender {
		width: 36rpx;
		height: 36rpx;
		margin-right: 8rpx;
	}

	.u-p-bg {
		position: absolute;
		top: 0;
	}

	.lb-p {
		position: relative;

		&-bg {
			position: absolute;
		}

		&-c {
			position: absolute;
			top: 160rpx;
			bottom: 60rpx;
			left: 80rpx;
			right: 80rpx;
		}
	}

	.card {
		background-color: #fff;
		padding: 10px;
	}

	.list-item {
		padding: 10px 0;
	}

	.list-item:not(:last-child) {
		border-bottom: 1px solid rgba($color: #333333, $alpha: 0.1);
	}

	.list-item image {
		width: 46rpx;
		height: 46rpx;
		margin-right: 10px;
	}

	.btn-deposit {
		color: #619AFF;
	}

	.vip-card {
		position: relative;

		&-content {
			position: absolute;
			top: 0;
			bottom: 0;
			right: 0;
			left: 0;
			padding: 20rpx;
			z-index: 99;
		}

		&-user-info {
			padding-right: 210rpx;
		}

		&-btn-rights {
			position: absolute;
			right: 0rpx;
			top: 40rpx;
			height: 70rpx;

			&-bg {
				width: 210rpx;
				height: 70rpx;
			}

			&-content {
				position: absolute;
				right: 0;
				top: 0;
				bottom: 0;
				left: 0;
				justify-content: center;
			}

			&-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 8rpx;
			}
		}

		color: #fff;
		border-radius: 40rpx;
		margin: 0 auto;
	}

	.name {
		font-size: 34rpx;
		word-wrap: break-word;
	}

	.img-code {
		width: 50rpx;
		height: 50rpx;
	}

	.img-wallet {
		width: 90rpx;
		height: 90rpx;
		position: absolute;
		right: 20rpx;
		top: 130rpx;
	}

	.wallet {
		position: relative;

		&-content {
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			padding: 40rpx;
			color: #FFFFFF;
		}

		&-icon {
			width: 110rpx;
			height: 110rpx;
		}
	}

	.qrcode-wrapper {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 998;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;

		&-content {
			&-qrcode {
				width: 200px;
				height: 200px;
			}
		}
	}

	.avatar-wrapper {
		background: none;
		padding: 0;
		width: 150rpx !important;
		height: 150rpx !important;
		margin: 0 !important;
	}

	.popup-exchange {
		width: 700rpx;
		height: 737rpx;
		position: relative;

		&-content {
			position: absolute;
			top: 160rpx;
			left: 54rpx;
			right: 54rpx;
			bottom: 260rpx;
			justify-content: space-between;

			input {
				border: 1px solid #CBCBCB;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 40rpx;
				padding: 0 20rpx;
			}
		}
	}

	.vip-indicator {
		margin-top: 10rpx;
		height: 8rpx;
		width: 84rpx;
		background-color: #DEDEDE;
		border-radius: 4rpx;

		&-thumb {
			width: 30rpx;
			background-color: #D61719;
			border-radius: 4rpx;
			left: 0;
		}

		&-thumb-right {
			left: 54rpx;
		}
	}

	.btn-set-nickname {
		background-image: linear-gradient(to right, #FD5C47, #FF9F43);
		width: 500rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		margin: 30rpx auto;
		font-size: 32rpx;
		color: #fff;
	}
</style>